package com.cxy.ch2.tools;


import java.util.concurrent.CountDownLatch;

import com.cxy.tools.SleepTools;

/**
 *类说明：演示CountDownLatch用法，
 * 共5个初始化子线程，6个闭锁扣除点，扣除完毕后，主线程和业务线程才能继续执行
 */
public class UseCountDownLatch {
	
    static CountDownLatch latch = new CountDownLatch(6);

    /*初始化线程*/
    private static class InitThread implements Runnable{

        public void run() {
        	System.out.println("Thread_"+Thread.currentThread().getId()
        			+" 准备初始化工作......");
            latch.countDown();
            for(int i =0;i<2;i++) {
            	System.out.println("Thread_"+Thread.currentThread().getId()
            			+" ........继续工作");
            }
        }
    }

    /*业务线程等待latch的计数器为0完成*/
    private static class BusiThread implements Runnable{

        public void run() {
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for(int i =0;i<3;i++) {
            	System.out.println("BusiThread_"+Thread.currentThread().getId()
            			+" 执行业务-----");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new Thread(new Runnable() {
            public void run() {
            	SleepTools.ms(1);
                System.out.println("Thread_"+Thread.currentThread().getId()
            			+" 就绪初始工作步骤1......");
                latch.countDown();
                System.out.println("开始第二步.......");
                SleepTools.ms(1);
                System.out.println("Thread_"+Thread.currentThread().getId()
            			+" 就绪初始工作步骤2......");
                latch.countDown();
            }
        }).start();
        new Thread(new BusiThread()).start();
        for(int i=0;i<=3;i++){
            Thread thread = new Thread(new InitThread());
            thread.start();
        }

        latch.await();
        System.out.println("主线程工作........");
    }
    /**
     *  Thread_21 准备初始化工作......
		Thread_23 准备初始化工作......
		Thread_24 准备初始化工作......
		Thread_22 准备初始化工作......
		Thread_24 ........继续工作
		Thread_23 ........继续工作
		Thread_21 ........继续工作
		Thread_23 ........继续工作
		Thread_24 ........继续工作
		Thread_22 ........继续工作
		Thread_22 ........继续工作
		Thread_21 ........继续工作
		Thread_19 就绪初始工作步骤1......
		开始第二步.......
		Thread_19 就绪初始工作步骤2......
		主线程工作........
		BusiThread_20 执行业务-----
		BusiThread_20 执行业务-----
		BusiThread_20 执行业务-----

     */
}
